rm(list=ls())
setwd("/Files for R/ReSTAT")
Peerz=read.csv("ResDay_ReSTAT.csv")

#convert dates into date format
Peerz$rec_in=as.Date(Peerz$rec_in, format='%d %b %y')
Peerz$rec_out=as.Date(Peerz$rec_out, format='%d %b %y')

library('Matrix')

##################################
### Build the peer matrix #########
###################################
# first generate an NxN matrix of null values 
peermatrix=matrix(0,length(Peerz$rec_out),length(Peerz$rec_out))

#Add a column to organize the 
Peerz=transform(Peerz,share=0, lastin=0, firstout=0)

   #Build peer measuPeerz
system.time(
for (k in 1:length(Peerz$numzz)){
  print(k)
  #make the subset
  samefacility=subset(Peerz, with(Peerz,labelfac61==labelfac61[k] & rec_in<=rec_out[k] & rec_out>=rec_in[k]))
  #build the time shared variable (is there a quicker way?)
  samefacility$firstout=ifelse(samefacility$rec_out<Peerz$rec_out[k], samefacility$rec_out, Peerz$rec_out[k])
  samefacility$lastin  =ifelse(samefacility$rec_in >Peerz$rec_in[k],  samefacility$rec_in,  Peerz$rec_in[k])
  samefacility$share=samefacility$firstout-samefacility$lastin
  #adding values to the peer matrix
  for(j in 1:length(samefacility$numzz)){
    peermatrix[k,samefacility$numzz[j]]=samefacility$share[j]
    peermatrix[k,k]=0
  }

  rm(samefacility)
}
)
peermatrix=Matrix(peermatrix, sparse=T)
save(peermatrix, file="peermatrixDay_ReSTAT.RData") 

